<template>
  <el-container>
    <BomTree style="margin-top: 16px" @on-choose-region="filetrStation" />
    <el-main>
      <div class="default-main ba-table-box">
        <TableHeader
          :buttons="[
            'refresh',
            'add',
            'edit',
            'remove',
            'comSearch',
            'columnDisplay',
            'upload',
            'export',
          ]"
          :quick-search-placeholder="placeholder"
          @action="baTable.onTableHeaderAction"
        />
        <!-- 要使用`el-table`组件原有的属性，直接加在Table标签上即可 -->
        <Table ref="tableRef" @action="baTable.onTableAction" />
        <!-- 表单 -->
        <PopupForm
          v-if="
            (baTable.form.operate !== 'upload' &&
              JSON.stringify(equipUnit.stationInfo) !== '{}' &&
              baTable.form.operate) ||
            baTable.form.operate === 'edit'
          "
        />
        <!-- 上传excel文件 -->
        <Upload
          v-if="baTable.form.operate && baTable.form.operate === 'upload'"
        />
      </div>
    </el-main>
  </el-container>
</template>
<script lang="ts" setup>
import { ref, provide, onMounted, reactive, onBeforeUnmount } from "vue";
import baTableClass from "@/utils/baTable";
import { baTableApi, operatorShowOff } from "@/utils/common"; // 导入表格api方法生成器
import { FactoryEquip } from "@/api/backend/index";
import Table from "@/components/table/index.vue";
import TableHeader from "@/components/table/header/index.vue";
import PopupForm from "./popupForm.vue";
import Upload from "./components/import.vue";
import { useRoute, useRouter } from "vue-router";
import { useNavTabs } from "@/store/navTabs";
import type { TableRow, TableColumn } from "@/utils/baTable"; //表格列行类型
import { useDictionary } from "@/store/backend/tool/dictionary";
import { useFactoryEquipment } from "@/store/backend/FactoryM/equipmentUnit";
import BomTree from "./components/aside.vue";
import { useFactoryStation } from "@/store/backend/FactoryM/stationInfo";
import useCurrentInstance from "@/utils/useCurrentInstance";
import { useModel } from "@/store/backend/DeviceM/model";
import { useAccessPoint } from "@/store/backend/AccessPointM/accessPoint";
import { useBomProcess } from "@/store/backend/BomM/bomProcess";
import { useBomRoute } from "@/store/backend/BomM/bomRoute";

// import { _post } from "@/utils/axios";
const placeholder = ref<string>("模糊搜索");
const tableRef = ref();
const route = useRoute();
const router = useRouter();
const navTabs = useNavTabs();
const dictionary = useDictionary();
const equipUnit = useFactoryEquipment();
const station = useFactoryStation();
const model = useModel();
const accessPoint = useAccessPoint();
const bomP = useBomProcess();
const bomR = useBomRoute();

//全局事件总线
const { proxy } = useCurrentInstance();

//字段显隐记忆功能
const filedShowOff = (filter: any) => {
  if ((navTabs as any).columnDisplayStoreMap) {
    return (navTabs as any).columnDisplayStoreMap.get(
      route.path + "/" + filter
    );
  }
  return true;
};
// 每页个数记忆功能 默认10个
const pageSizeKeep = () => {
  if ((navTabs as any).pageSizeMap) {
    return (navTabs as any).pageSizeMap.get(route.path + FactoryEquip)
      ? (navTabs as any).pageSizeMap.get(route.path + FactoryEquip)
      : 10;
  }
  return 10;
};

const baTable = new baTableClass(
  new baTableApi(FactoryEquip),
  {
    pk: "id", //区域ID
    column: [
      { type: "selection", align: "center", operator: false },
      // {
      //   show: filedShowOff("code"),
      //   label: "车间代码",
      //   prop: "code",
      //   align: "left",
      // },
      {
        show: filedShowOff("name"),
        label: "车间名称",
        prop: "name",
        align: "left",
      },
      {
        show: filedShowOff("equipmentCode"),
        label: "设备编码",
        prop: "equipmentCode",
        align: "left",
      },
      {
        show: filedShowOff("equipmentName"),
        label: "设备名称",
        prop: "equipmentName",
        align: "left",
      },
      {
        show: filedShowOff("equipmentType"),
        label: "设备型号",
        prop: "equipmentType",
        align: "left",
        operatorPlaceholder: "模糊搜索",
      },
      // {
      //   show: filedShowOff("runTime"),
      //   label: "额定运行时间/小时",
      //   prop: "runTime",
      //   align: "left",
      //   operatorPlaceholder: "模糊搜索",
      // },
      {
        show: operatorShowOff([
          route.path + "/edit",
          route.path + "/add",
          route.path + "/remove",
        ]),
        label: "操作",
        align: "center",
        width: "130",
        operator: false,
        render: "buttons",
        fixed: "right",
        buttons: [
          {
            render: "tipButton",
            name: "edit",
            title: "编辑",
            text: "",
            type: "primary",
            icon: "iconfont icon-pencil",
            class: "table-row-edit",
            disabledTip: false,
            // 按钮是否显示，请返回布尔值
            display: (row: TableRow, field: TableColumn) => {
              return true;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
          {
            render: "tipButton",
            name: "info",
            title: "详情",
            text: "",
            type: "primary",
            icon: "iconfont icon-chaxunyujisuan",
            class: "table-row-edit",
            disabledTip: false,
            // 按钮是否显示，请返回布尔值
            display: (row: TableRow, field: TableColumn) => {
              return true;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
          {
            render: "confirmButton",
            name: "remove",
            title: "删除",
            text: "",
            type: "danger",
            icon: "el-icon-DeleteFilled",
            class: "table-row-delete",
            popconfirm: {
              confirmButtonText: "删除",
              cancelButtonText: "取消",
              confirmButtonType: "danger",
              title: "确定删除所选项吗",
            },
            disabledTip: false,
            // 按钮是否显示，请返回布尔值
            display: (row: TableRow, field: TableColumn) => {
              return true;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
        ],
      },
    ],
    filter: {
      pageNum: 1,
      pageSize: pageSizeKeep(),
    },
  },
  {
    defaultItems: {},
  }
);

//接收工作中心树传递过来的数据
const filetrStation = (row: any, node: any) => {
  console.log("接收工作中心树传递过来的数据", row, node);

  if (node.checkedKeys.length == 0) {
    //表示取消选择直接调用刷新表单方法
    // baTable.comSearch.form = Object.assign(baTable.comSearch.form, {
    //   regions: region.regionIds + "",
    // });
    // baTable.onTableHeaderAction("refresh", {});
    equipUnit.$patch((state: any) => {
      state.stationInfo = {};
    });
  } else {
    baTable.comSearch.form.name = row.label;
    baTable.comSearch.form.deptId = row.id;
    baTable.getList(FactoryEquip);
    equipUnit.$patch((state: any) => {
      state.stationInfo = row;
    });
    bomR.$patch((state: any) => {
      state.bomTreeParent = node.halfCheckedNodes[0]; //父级物料编码
    });
  }
};

//跳转详情页
const infoButtonClick = (id: number, row: any) => {
  console.log("id", id, "row", row);
  equipUnit.$patch((state) => {
    state.single = row;
    state.id = row.id;
  });
  router.push({
    path: "/admin/EquipmentUnit/detail",
    query: { materialCode: row.productCode, materialType: row.materialType },
  });
};

onMounted(() => {
  //将table的ref给到table类
  baTable.table.ref = tableRef.value;
  baTable.mount();
  baTable.getList(FactoryEquip);

  /**
   * 表格内的按钮响应
   * @param name 按钮name
   * @param row 被操作行数据
   */
  proxy.eventBus.on(
    "onTableButtonClick",
    (data: { name: string; row: TableRow }) => {
      switch (data.name) {
        case "info":
          //详情页面
          infoButtonClick(
            (data.row as TableRow)[baTable.table.pk!],
            data.row as any
          );
          break;
      }
    }
  );
});

onBeforeUnmount(() => {
  equipUnit.$patch((state: any) => {
    state.stationInfo = {};
  });
});
// 实例化表格后，将 baTable 的实例提供给上下文
provide("baTable", baTable);
provide("dictionary", dictionary);
provide("equipUnit", equipUnit);
provide("station", station);
provide("model", model);
provide("accessPoint", accessPoint);
provide("bomP", bomP);
provide("bomR", bomR);
</script>
<style lang="scss" scoped>
.default-main {
  margin: 0px !important;
}
</style>
